import matplotlib.pyplot as plt
import numpy as np

import os
path = os.path.dirname(__file__) # 先找到当前文件 a.py 所在的目录
file_name1 = os.path.join(path,'A_point.txt') # 拼接文件的路径
file_name2 = os.path.join(path,'A_error.txt')
a = []
b = []
file1 = open(file_name1, mode = 'r')
for line in file1:
    line = line.split()
    a.append(line)
file1.close()

file2 = open(file_name2, mode = 'r')
for line in file2:
    line = line.split()
    b.append(line)
file2.close()

a1 = []
for m in a:
    a1.append(float(m[0]))
a = a1
b1 = []
for m in b:
    b1.append(float(m[0]))
b = b1

n = 100
x = np.linspace(-1,1,n)
y = 1/(1+25*x*x)
for m in range(0,3):#拟合图像
    Y = np.zeros((n,5))
    B = np.zeros((n,5))
    p = 10*n*m
    for k in range(0, 5):
        for i in range(0, n):
            Y[i][k] = a[p]
            p = p + 1
    for k in range(0,5):
        for i in range(0,n):
            B[i][k] = a[p]
            p = p + 1
    Y1 = np.array(Y)
    B1 = np.array(B)
    plt.figure(1)
    plt.plot(x,y,'--')
    for i in range(0, 5):
        plt.plot(x,Y1[:,i])
    plt.legend(['f','N=6','N=11','N=21','N=41','N=81'])
    if m==0:
        plt.savefig(os.path.join(path,"figure/A_ppForm1.png"))
    if m==1:
        plt.savefig(os.path.join(path,"figure/A_ppForm2.png"))
    if m==2:
        plt.savefig(os.path.join(path,"figure/A_ppForm3.png"))
    plt.figure(2)
    plt.plot(x,y,'--')
    for i in range(0,5):
        plt.plot(x,B1[:,i])
    plt.legend(['f','N=6','N=11','N=21','N=41','N=81'])
    if m==0:
        plt.savefig(os.path.join(path,"figure/A_B_spline1.png"))
    if m==1:
        plt.savefig(os.path.join(path,"figure/A_B_spline2.png"))
    if m==2:
        plt.savefig(os.path.join(path,"figure/A_B_spline3.png"))

d = 8
E1 = np.zeros((d,3))
E2 = np.zeros((d,3))
for m in range(0,3):
    c = 2*d*m
    for i in range(0,d):
        E1[i][m] = b[c+i]
        E2[i][m] = b[c+d+i]
E11 = np.array(E1)
E22 = np.array(E2)
N = np.array([6, 11, 21, 41, 81])
plt.figure(3)
for m in range(0,3):
    plt.plot(N,E11[0:5,m])
plt.legend(['way=1','way=2','way=3'])
plt.savefig(os.path.join(path,"figure/A_ppForm_error.png"))
plt.figure(4)
for m in range(0,3):
    plt.plot(N,E22[0:5,m])
plt.legend(['way=1','way=2','way=3'])
plt.savefig(os.path.join(path,"figure/A_B_spline_error.png"))

M=np.zeros((7,1))
for i in range(0,7):
    M[i][0] = np.log(E11[i,0]/E11[i+1,0])
M1=np.array(M)
z = np.array([1, 2, 3, 4, 5, 6, 7])
plt.figure(5)
plt.plot(z,M1)
plt.savefig(os.path.join(path,"figure/A_convergence.png"))




    